package fl.android.ui;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLSurfaceView;
import fl.android.Audio;
import fl.android.Note.Voice;
import fl.android.Project;

public class UIRenderer implements GLSurfaceView.Renderer {

	public Button[][] buttons;
	public PianoRoll piano = new PianoRoll();
	public int width, height;
	
	public static float[][] colors = new float[][] {
		{0f,0f,1f,1f},
		{0f,1f,1f,1f},
		{1f,0f,1f,1f},
		{1f,1f,1f,1f}
	};

	public UIRenderer() {
	}

	public void onDrawFrame(GL10 gl) {
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

		for (int x = 0; x < buttons.length; x++) {
			for (int y = 0; y < buttons[x].length; y++) {
				buttons[x][y].draw(gl);
			}
		}

		piano.render(gl);

		float off = 1 / 1000f;
		Rect.render(gl, off, off, 0f, .25f - off * 2, .1f - off * 2f,
				new float[] { 0f, .75f, 0f, 1f });
		Rect.render(gl, off + .25f, off, 0f, .25f - off * 2, .1f - off * 2f,
				new float[] { .75f, 0f, 0f, 1f });

		for (int i = 0; i < 4; i++) {
			float[] color = colors[i].clone();
			if (Project.selected.ordinal() != i) {
				color[0] /= 4f;
				color[1] /= 4f;
				color[2] /= 4f;
			}
			Rect.render(gl, .5f + i * .125f + off, off, 0f, .125f - off * 2f,
					.1f - off * 2f, color);
		}
	}

	public void onSurfaceChanged(GL10 gl, int width, int height) {
		this.width = width;
		this.height = height;
		gl.glViewport(0, 0, width, height);
		gl.glMatrixMode(GL10.GL_PROJECTION);
		gl.glLoadIdentity();
		gl.glOrthof(0f, 1f, 0f, 1f, -1f, 1f);
		gl.glMatrixMode(GL10.GL_MODELVIEW);
		gl.glLoadIdentity();

		int bx = 16;
		int by = 13;
		float off = 1f / 1000f;
		float sx = .2f;
		float twid = .8f;
		float bwid = twid / bx;
		float bhei = .9f / by;
		buttons = new Button[bx][by];
		for (int x = 0; x < bx; x++) {
			for (int y = 0; y < by; y++) {
				buttons[x][y] = new Button(sx + bwid * x + off, bhei * y + off
						+ .1f, bwid - off * 2, bhei - off * 2, x, y);
			}
		}
	}

	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		gl.glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
		gl.glShadeModel(GL10.GL_SMOOTH);
		gl.glClearDepthf(1.0f);
		gl.glEnable(GL10.GL_DEPTH_TEST);
		gl.glDepthFunc(GL10.GL_LEQUAL);
		gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
	}

	public void touch(int tx, int ty) {
		float dx = (float) tx / width;
		float dy = (float) ty / height;
		if (dy < .1) {
			if (dx < .25)
				Audio.Play();
			else if (dx < .5)
				Audio.Stop();
			else {
				Project.selected = Voice.values()[(int) ((dx - .5) / .125)];
			}
			return;
		}
		for (int x = 0; x < buttons.length; x++) {
			for (int y = 0; y < buttons[x].length; y++) {
				float bl = buttons[x][y].x;
				float bb = buttons[x][y].y;
				float br = buttons[x][y].width + bl;
				float bt = buttons[x][y].height + bb;
				if (dx >= bl && dx <= br && dy >= bb && dy <= bt) {
					buttons[x][y].toggle();
					return;
				}
			}
		}
	}

}
